<template>
  <div class="content-wrap" v-loading="loading">
    <div class="main-container">
      <div class="operate-container">
        <div class="operate-container_left">
          <el-button
            type="primary"
            icon="Plus"
            @click="openCreatePlan({ plan: null, type: 'addMaster' })"
            >新增计划</el-button
          >
          <el-button icon="CopyDocument" @click="openSelectTemp">选择模板</el-button>
          <el-button icon="Position" @click="handlePlanReleased" :disabled="!ids.length"
            >计划下达</el-button
          >
          <el-button type="danger" @click="removePlans" :disabled="!ids.length">删除计划</el-button>
        </div>
        <div class="operate-container_right">
          <!-- <img class="toggle" @click="toggleChart" src="/img/views/pdp/toggle.svg" alt="" /> -->
        </div>
      </div>
      <div class="table-container">
        <el-table
          :data="dataList"
          :tree-props="treeProps"
          row-key="id"
          @selection-change="handleSelectionChange"
          height="100%"
          @row-click="openPlanPerformRef"
        >
          <template #empty>
            <div class="no-data">
              <img class="no-data-img" src="/img/views/pdp/no-data.png" alt="" />
              <div class="no-data-desc">暂无信息，请创建计划</div>
              <el-button type="primary" icon="CopyDocument" @click="openSelectTemp"
                >用模板创建</el-button
              >
            </div>
          </template>
          <el-table-column width="20" type="">
            <template #default="scoped">
              <el-popover
                placement="bottom-start"
                :width="112"
                trigger="hover"
                popper-style="padding-left: 0;padding-right: 0;"
              >
                <template #reference>
                  <el-icon class="more-filled" @click.stop><MoreFilled /></el-icon>
                </template>
                <ul class="list-group">
                  <li class="list-item" @click.stop="handlePlanReleased(scoped.row)">
                    <div class="list-item_name">计划下达</div>
                  </li>
                  <li class="list-item" @click.stop="openCreateChildPlan(scoped.row, 'addChild')">
                    <div class="list-item_name">创建子计划</div>
                  </li>
                  <li class="list-item" @click.stop="openPlanEdit(scoped.row)">
                    <div class="list-item_name">编辑</div>
                  </li>
                  <li class="list-item" @click.stop="removePlan(scoped.row)">
                    <div class="list-item_name">删除计划</div>
                  </li>
                </ul>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column type="selection" width="30" align="center" />
          <el-table-column prop="planName" label="任务" min-width="240">
            <template #default="scoped">
              <span class="plan-name">
                <span
                  class="plan-type"
                  :style="{ backgroundColor: getColor(scoped.row.businessCategoryId) }"
                >
                  <dc-dict
                    type="text"
                    :options="DC_PMS_TEMPITEM_TYPE"
                    :value="scoped.row.businessCategoryId"
                    v-if="scoped.row.businessCategoryId"
                  />
                </span>
                {{ scoped.row.planName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="handlePersonId" label="处理人" width="140" align="center">
            <template #default="scoped">
              <dc-view v-model="scoped.row.handlePersonId" objectName="user" showKey="realName" />
            </template>
          </el-table-column>
          <el-table-column prop="planStatus" label="状态" align="center" width="140">
            <template #default="scoped">
              <dc-dict :options="DC_PMS_PLAN_STATUS" :value="scoped.row.planStatusId" />
            </template>
          </el-table-column>
          <el-table-column prop="startDate" label="开始日期" align="center" width="140" />
          <el-table-column prop="endDate" label="结束日期" align="center" width="140" />
          <el-table-column prop="isMilestone" label="是否里程碑" align="center" width="140">
            <template #default="scoped">
              <el-switch
                v-model="scoped.row.isMilestone"
                @click.stop="toggle(scoped.row)"
                style="
                  --el-switch-on-color: rgba(35, 198, 159, 0.3);
                  --el-switch-off-color: #eff1f3;
                  --el-color-white: #23c69f;
                "
              />
            </template>
          </el-table-column>
          <el-table-column prop="output" label="输出" align="center" width="140">
            <template #default="scoped">{{ scoped.row.output || '-' }}</template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
  <!-- 模板选择 -->
  <selectTemp
    ref="selectTempRef"
    :categoryId="categoryId"
    :projectCaseId="projectCaseId"
    :projectId="projectId"
    @confirm="getData()"
  />
  <!-- 新增计划或者编辑计划 -->
  <createPlan
    ref="createPlanRef"
    :projectInfo="info"
    :projectCaseId="projectCaseId"
    :projectId="projectId"
    @confirm="getData()"
  />
  <!-- 创建子计划 -->
  <createChildPlan
    ref="createChildPlanRef"
    :projectInfo="info"
    :projectCaseId="projectCaseId"
    :projectId="projectId"
    @confirm="getData()"
  />
  <!-- 计划执行 -->
  <planPerform ref="planPerformRef" :projectInfo="info" @confirm="getData()" />
</template>
<script setup name="ProjectPlan">
import { reactive, toRefs, onMounted } from 'vue';
import Api from '@/api/index';
import { arrayToTree } from '@/utils/util';
import selectTemp from './components/selectTemp.vue';
import createPlan from './components/createPlan.vue';
import createChildPlan from './components/createChildPlan.vue';
import planPerform from './components/planPerform.vue';

const { proxy } = getCurrentInstance();

const { DC_PMS_PLAN_STATUS, DC_PMS_TEMPITEM_TYPE } = proxy.useCache([
  { key: 'DC_PMS_PLAN_STATUS' },
  { key: 'DC_PMS_TEMPITEM_TYPE' },
]);

const route = useRoute();

const compData = reactive({
  loading: false,
  selectTempRef: null,
  createPlanRef: null,
  planPerformRef: null,
  createChildPlanRef: null,
  dataList: [],
  info: {},
  projectCaseId: null,
  projectId: null,
  treeProps: {
    checkStrictly: false,
  },
  ids: [],
});

const {
  loading,
  selectTempRef,
  createPlanRef,
  planPerformRef,
  createChildPlanRef,
  dataList,
  info,
  projectCaseId,
  projectId,
  treeProps,
  ids,
} = toRefs(compData);

const categoryId = computed(() =>
  projectCaseId.value ? '1854323339350822914' : '1854323301367205889'
);

onMounted(() => {
  projectCaseId.value = route.params.projectCaseId;
  projectId.value = route.params.projectId;
  getData();
  if (projectId.value) getDetail();
});

// 详情
const getData = async () => {
  try {
    loading.value = true;
    const res = await Api.pdp.planItem.getPlanitemList({
      projectId: projectId.value,
      projectCaseId: projectCaseId.value,
      size: 999999,
      current: 1,
    });
    const { code, data } = res.data;
    if (code === 200) {
      const arr = data.records.map(item => {
        item.isMilestone = item.isMilestone === 0 ? true : false;
        return item;
      });
      dataList.value = arrayToTree(arr);
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
};

// 详情
const getDetail = async () => {
  try {
    loading.value = true;
    const res = await Api.pdp.project.detail({ id: projectId.value });
    const { code, data } = res.data;
    if (code === 200) {
      info.value = data;
    }
    loading.value = false;
  } catch (e) {
    loading.value = false;
  }
};

// 打开选择计划模板弹窗
const openSelectTemp = () => selectTempRef.value.openDialog();

// 打开新增计划抽屉
const openCreatePlan = ({ plan, type }) => {
  createPlanRef.value.openDrawer({ plan, type });
};

// 打开新增子计划
const openCreateChildPlan = (plan, type) => {
  createChildPlanRef.value.openDrawer({ plan, type });
};

// 打开编辑子计划或者主计划弹窗
const openPlanEdit = row => {
  const type = row?.parentId ? 'editChild' : 'editMaster';
  switch (type) {
    case 'editMaster':
      createPlanRef.value.openDrawer({ plan: row, type });
      break;
    case 'editChild':
      const parentPlan = proxy.findNode(dataList.value, row.parentId);
      createChildPlanRef.value.openDrawer({ plan: row, type, parentPlan });
      break;
  }
};

// 处理计划执行
const openPlanPerformRef = plan => {
  planPerformRef.value.openDrawer(plan);
};

// 删除计划
const removePlan = row => {
  if (row.planStatusId === '1866033974148980737')
    return proxy.$message({
      type: 'warning',
      message: '非规划中不可删除!',
    });
  proxy
    .$confirm(`确认是否删除任务名称为“${row.planName}”的计划?`, {
      confirmButtonText: '删除',
      cancelButtonText: '关闭',
      type: 'warning',
    })
    .then(async () => await Api.pdp.planItem.remove({ ids: row.id }))
    .then(() => {
      getData();
      proxy.$message({
        type: 'success',
        message: '删除成功!',
      });
    })
    .catch(() => {});
};

// 删除计划
const removePlans = row => {
  proxy
    .$confirm('确认是否删除选中的计划？', {
      confirmButtonText: '删除',
      cancelButtonText: '关闭',
      type: 'warning',
    })
    .then(async () => await Api.pdp.planItem.remove({ ids: ids.value }))
    .then(() => {
      getData();
      proxy.$message({
        type: 'success',
        message: '删除成功!',
      });
    })
    .catch(() => {});
};

// 计划下达
const handlePlanReleased = plan => {
  if (!ids.value.length && !plan.id) return;
  const planIds = ids.value.length ? ids.value.slice(',') : plan.id;
  const text = plan ? `确认是否下达选中的计划?` : `确认是否下达名称为“${plan.planName}”的计划?`;
  proxy
    .$confirm(text, {
      confirmButtonText: '确认下达',
      cancelButtonText: '关闭',
      type: 'warning',
    })
    .then(async () => await Api.pdp.planItem.sendDownPlan({ dcPmsPlanItemIds: planIds }))
    .then(res => {
      const { msg } = res.data;
      getData();
      proxy.$message({
        type: 'success',
        message: msg,
      });
    })
    .catch(() => {});
};

const toggle = row => {
  const timer = setTimeout(async () => {
    const res = await Api.pdp.planItem.submit({
      id: row.id,
      isMilestone: row.isMilestone ? 0 : 1,
    });
    const { code } = res.data;
    if (code === 200) {
      getData();
    }
    clearTimeout(timer);
  });
};

const handleSelectionChange = val => {
  ids.value = val.map(({ id }) => id).join(',');
};

// 获取颜色
const getColor = businessCategoryId => {
  switch (businessCategoryId) {
    case '1859779038095085570':
      return '#11AFA7';
    case '1859779087373963266':
      return '#83CF5C';
    case '1862011185801105410':
      return '#168BE8';
    case '1862011232290770945':
      return '#994FE1';
    case '1867000908414631938':
      return '#000000';
    case '1878644432190779393':
      return '#cccccc';
  }
};
</script>
<style lang="scss">
.statistics-desc .el-progress-bar__inner {
  background: linear-gradient(90deg, #ffd1ac 0%, #f29346 100%);
}
</style>
<style lang="scss" scoped>
.content-wrap {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .main-container {
    display: flex;
    flex-direction: column;
    padding: 0 16px;
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    .operate-container .toggle {
      cursor: pointer;
    }
    .table-container {
      .plan-type {
        margin-right: 5px;
        padding: 2px 7px;
        border-radius: 3px;
        font-weight: 400;
        font-size: 12px;
        color: #fff;
        line-height: 10px;
      }
      .plan-name {
        cursor: pointer;
      }
    }
  }
}
</style>
